const mongoose = require('mongoose');

// 连接数据库
mongoose.connect('mongodb://localhost:27017/graduation_project', {
  useNewUrlParser: true,
  useFindAndModify: false
});

// 连接验证
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function(callback) {
  console.log('数据库连接成功');
});

// 毕业设计需要的数据Schema
const MachineDataSchema = new mongoose.Schema({
  key: {
    type: Number,
    required: true
  },
  machineNumber: {
    type: Number,
    required: true
  },
  light: {
    type: Number,
    required: true
  },
  temperature: {
    type: Number,
    required: true
  },
  humidity: {
    type: Number,
    required: true
  },
  smoke: {
    type: Number,
    required: true
  }
});

// 用户信息集合
const UserSchema = new mongoose.Schema(
  {
    userName: {
      type: String,
      required: true
    },
    password: {
      type: String,
      required: true
    }
  },
  { versionKey: false }
);
// 实例化集合
const MachineData = mongoose.model('MachineData', MachineDataSchema);
const Users = mongoose.model('User', UserSchema);

// 获取数据库数据
const getMachineData = function(callback) {
  MachineData.find({}, (err, result) => {
    if (err) throw new Error('查询数据失败');
    callback(result);
  });
};

// 获取单个设备数据
const getOneMachine = function(machineNumber, callback) {
  MachineData.find(
    {
      machineNumber
    },
    (err, result) => {
      if (err) throw new Error('查询数据失败');
      callback(result);
    }
  );
};

// 数据库用户信息匹配
const findUser = function(userName, password, callback) {
  Users.findOne({ userName: userName }, (err, result) => {
    if (err) throw new Error('查询数据库出错');
    let flag = false;
    try {
      if (password != result.password) {
        console.log('账号或密码错误');
        flag = false;
      } else {
        console.log('登录成功');
        flag = true;
      }
    } catch (error) {
      console.log('账号或密码错误');
    }
    console.log(flag);
    callback(flag);
  });
};

// 数据库插入操作
const insert = function(userName, password, callback) {
  Users.insertMany(
    { userName: userName, password: password },
    (err, result) => {
      if (err) callback(false);
      console.log('由dbController第107行打印' + result);
      callback(true);
    }
  );
};
// 导出数据
exports.getMachineData = getMachineData;
exports.getOneMachine = getOneMachine;
exports.findUser = findUser;
exports.insert = insert;

//! 单元测试
//* 获取数据库数据模块，测试成功
// getMachineData((result) => {
//   console.log(result);
// })

// insert('111', '111', flag => {
//   console.log(flag);
// });
